<template>
  <div class="app-container">
<!--    <div class="filter-container">-->
<!--      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="80px" class="searchform" inline>-->
<!--        <el-form-item :label="$t('bs.processName')" prop="url">-->
<!--          <el-input-->
<!--            v-model="listQuery.technology_name"-->
<!--            class="filter-item"-->
<!--            placeholder="工艺名称"-->
<!--            style="width: 204px;"-->
<!--            @keyup.enter.native="handleFilter"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="类别" prop="url">-->
<!--          <el-select v-model="listQuery.dev_type" clearable>-->
<!--            <el-option v-for="(item,k) in technology_type_option" :key="k" :value="item.dict_key"-->
<!--                       :label="item.dict_value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-button v-waves class="filter-item" @click="handleFilter">-->
<!--          {{ $t('table.search') }}-->
<!--        </el-button>-->
<!--        &lt;!&ndash;        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">&ndash;&gt;-->
<!--        &lt;!&ndash;          {{ $t('table.add') }}&ndash;&gt;-->
<!--        &lt;!&ndash;        </el-button>&ndash;&gt;-->
<!--      </el-form>-->

<!--    </div>-->

    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;">
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate()"
            v-bp="'/bs/technology/edit'"
          >
            {{$t("bs.add")}}
          </el-button>
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="expandAll"
          >
            全部展开
          </el-button>
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="collapseAll"
          >
            全部折叠
          </el-button>
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox v-for="(item,k) in fileds" :key="k" v-model="item.is_show" false-label="0" true-label="1">
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        row-key="id"
        style="width: 100%;"
        highlight-current-row
        ref="mytable"
      >
        <el-table-column v-if="fileds.technology_name.is_show==1" :label="$t('bs.processName')">
          <template slot-scope="{row}">
            {{ row.technology_name }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.inc_type.is_show==1" label="类别">
          <template slot-scope="{row}">
            {{ row.inc_type }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="right" class-name="small-padding fixed-width" width="200" >
          <template slot-scope="{row,$index}">
            <el-button  v-bp="'/bs/technology/edit'"  v-if="row.parent_id=='0'" size="small" @click="handleCreate(row.id)">
              添加工艺细分
            </el-button>
            <el-button circle icon="el-icon-edit"  v-bp="'/bs/technology/view'" size="small" @click="handleUpdate(row)"/>

            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDelete([row.id])"
            >
              <el-button
                v-bp="'/bs/technology/edit'"
                slot="reference"
                style="margin-left: 8px"
                circle
                icon="el-icon-delete"
                size="small"
              />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>



    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">
          <el-col :span="24" v-if="temp.parent_id>0">
            <el-form-item label="上节工艺" prop="parent_id">
              <el-select v-model="temp.parent_id">
                <el-option v-for="(item,k) in TechonlogyOption" :key="k" :value="item.id"
                           :label="item.technology_name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工艺分类" prop="inc_type">
              <el-select v-model="temp.inc_type">
                <el-option v-for="(item,k) in technology_type_option" :key="k" :value="item.dict_key"
                           :label="item.dict_value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('bs.processName')" prop="technology_name">
              <el-input v-model="temp.technology_name"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('bs.sort')" prop="px">
              <el-input v-model="temp.px" type="number"/>
            </el-form-item>
          </el-col>
                    <el-col :span="24">
                      <el-form-item :label="$t('bs.picture')" prop="img">
                        <div style="width: 100px;height: 100px;border:1px solid #f0f2f5;border-radius: 5px">
                          <el-upload
                              class="avatar-uploader"
                              :action="$UpFile"
                              :data="updata"
                              :headers="upheaders"
                              :show-file-list="false"
                              :on-success="handleAvatarSuccess"
                              :before-upload="beforeAvatarUpload">
                            <img v-if="temp.img" :src="temp.img" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                        </div>

                      </el-form-item>

                    </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary"  v-bp="'/bs/technology//edit'" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchDict, fetchTree} from '@/api/common'
import {getTechonlogyCat} from '@/api/technology'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect'
import {getToken} from "@/utils/auth"; // secondary package based on el-pagination

export default {
  name: 'SlTechnology',
  components: {CyTreeSelect, Pagination},
  directives: {waves},
  data() {
    return {
      checked: true,
      tablesetvisible: false,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      upheaders: {},
      updata: {},
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      showReviewer: false,
      temp: {
        id: '', parent_id: '0', technology_name: '', inc_type: '',img:"",px:50,
      },
      fileds: {
        technology_name: {filed: 'technology_name', title: '工艺名称', is_show: '1'},
        inc_type: {filed: 'inc_type', title: '类别', is_show: '1'}
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        technology_name: [{required: true, message: '工艺名称不能为空', trigger: 'change'}],
        inc_type: [{ required: true, message: '请选择工艺分类', trigger: 'change' }]
      },
      downloadLoading: false,
      TechonlogyOption: [],
      technology_type_option: [],
      isExpand:true,

    }
  },

  created() {
    this.getList()
    this.upheaders = {
      AccessToken: getToken()
    }
  },
  methods: {
    expandAll(){
      this.isExpand=true;
      this.$nextTick(() => {
        this.forArr(this.list, this.isExpand)
      })
    },
    collapseAll(){
      this.isExpand=false;
      this.$nextTick(() => {
        this.forArr(this.list, this.isExpand)
      })
    },
    forArr(arr, isExpand) {
      arr.forEach(i => {
        // toggleRowExpansion见element文档
        this.$refs.mytable.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async getOption() {
      const option = await getTechonlogyCat()
      if (!option.data.items) {
        option.data.items = []
      }
      // option.data.items.unshift({id: '0', technology_name: '顶级工艺', parent_id: '0'})
      this.TechonlogyOption = option.data.items.filter(obj => obj.parent_id === '0')
      fetchDict('工艺分类').then((res) => {
        if (res.data.items) {
          this.technology_type_option = res.data.items
        }
      })
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchTree(this.listQuery, '/api/techonlogy/get_tree').then(response => {
        console.log(response)
        // if (response.data && response.data.items) {
          this.list = response.data
        //   this.total = response.data.count
        // }

        this.listLoading = false
        this.getOption()
      })
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)
      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          queryParma['and'] = [
            {field: listkeys[i], operator: 'like', value: '%' + this.listQuery[listkeys[i]] + '%'}
          ]
        }
      }
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '', parent_id: '0', technology_name: '', inc_type: '',img:"",px:50,
      }
    },
    handleCreate(pid='') {
      this.resetTemp()
      this.dialogStatus = 'create'
      if(pid)
      {
        this.temp.parent_id=pid;
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'technology',
            add: this.temp
          }
          createData({data: [data]}, 'sl_technology').then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'technology',
            update: this.temp
          }
          updateData({data: [data]}, 'sl_technology').then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleDelete(ids) {
      delData({id: ids.join(',')}, 'sl_technology').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleAvatarSuccess(res, file) {

      console.log('上传成功', this.temp.img)
      this.temp.img = process.env.VUE_APP_BASE_URL+file.response.data;
      console.log('上传成功', this.temp.img)
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === 'image/jpeg'||file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 280px;
}
.avatar-uploader{
  width: 100px;
  height: 100px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

